package com.sitech.portal.system.action;

import com.ibatis.common.resources.Resources;
import com.sitech.BaseConst;
import com.sitech.ibnms.common.form.TreeNode;
import com.sitech.ibnms.common.service.IAsyncTreeService;
import com.sitech.ibnms.core.IPage;
import com.sitech.ibnms.core.JGridBaseAction;
import com.sitech.ibnms.util.AppException;
import com.sitech.ibnms.util.JSONUtil;
import com.sitech.portal.server.service.IPortalService;
import com.sitech.portal.system.domain.TblSYS_LOGINMSG;
import com.sitech.portal.system.domain.TblSYS_USER_ROLE;
import com.sitech.portal.system.form.PortalForm;
import com.sitech.portal.system.form.UserForm;
import com.sitech.portal.system.form.UserPortalForm;
import com.sitech.portal.system.service.*;
import com.sitech.portal.util.CommUtil;
import com.sitech.portal.util.UrlSSOUtil;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;


public class PortalAction extends JGridBaseAction{

	private String subSystemJsonList;
	private List subSystemList;
	private List shortcutList = new ArrayList();
	private List firstLevelModuleList = new ArrayList();
	private PortalForm filter = new PortalForm();
	private TblSYS_LOGINMSG user = new TblSYS_LOGINMSG();
	private IPublicSysService publicSysService;
	private ISysLogInmsgService sysLogInmsgService;
	private ISysUserPrivilegeService sysUserPrivilegeService;
	private ISysSubSystemService sysSubSystemService;
	private ISysModuleService sysModuleService;
	private ISysUserShortcutService sysUserShortcutService;
	private ISysParaService sysParaService;
	private IPortalService portalService;
	private ISysUserRoleService sysUserRoleService;
	private ISysRoleService sysRoleService;
	private ISysPostTimeService sysPostTimeService;
	private ISysLogService sysLogService;
	private ISysUserPortalService userPortalService;
	private ISysUserPanelOrderService sysUserPanelOrderService;
	private String flag = null;
	private HashMap porletsMap = new HashMap();
	private List porletsList = new ArrayList();
	private Map userSetting;
	private Map layout;
	private String LOGOUT_LINK;
	private List LOGOUT_LINKS;
	private UserForm theForm = new UserForm();
	private List deptlist;
	private List canRoleList;
	private List roleList;
	private IAsyncTreeService portalTreeService;
	private String module_id;
	private String id;
	private List<HashMap> userPorlets;
	private UserPortalForm portalForm = new UserPortalForm();
	private String helpId;
	private String helpMsg;
	private String content;
    private ISysLogUserChangeService sysLogUserChangeService;
	HashMap panelData = new HashMap();

    public ISysLogUserChangeService getSysLogUserChangeService() {
        return sysLogUserChangeService;
    }

    public void setSysLogUserChangeService(ISysLogUserChangeService sysLogUserChangeService) {
        this.sysLogUserChangeService = sysLogUserChangeService;
    }

    public ISysUserRoleService getSysUserRoleService() {
		return sysUserRoleService;
	}

	public void setSysUserRoleService(ISysUserRoleService sysUserRoleService) {
		this.sysUserRoleService = sysUserRoleService;
	}

	public ISysRoleService getSysRoleService() {
		return sysRoleService;
	}

	public void setSysRoleService(ISysRoleService sysRoleService) {
		this.sysRoleService = sysRoleService;
	}

	public ISysPostTimeService getSysPostTimeService() {
		return sysPostTimeService;
	}

	public void setSysPostTimeService(ISysPostTimeService sysPostTimeService) {
		this.sysPostTimeService = sysPostTimeService;
	}

	public ISysLogService getSysLogService() {
		return sysLogService;
	}

	public void setSysLogService(ISysLogService sysLogService) {
		this.sysLogService = sysLogService;
	}

	public String getLOGOUT_LINK() {
		return LOGOUT_LINK;
	}

	public void setLOGOUT_LINK(String logout_link) {
		LOGOUT_LINK = logout_link;
	}

	public List getLOGOUT_LINKS() {
		return LOGOUT_LINKS;
	}

	public void setLOGOUT_LINKS(List logout_links) {
		LOGOUT_LINKS = logout_links;
	}

	public UserForm getTheForm() {
		return theForm;
	}

	public void setTheForm(UserForm theForm) {
		this.theForm = theForm;
	}

	public List getDeptlist() {
		return deptlist;
	}

	public void setDeptlist(List deptlist) {
		this.deptlist = deptlist;
	}

	public List getCanRoleList() {
		return canRoleList;
	}

	public void setCanRoleList(List canRoleList) {
		this.canRoleList = canRoleList;
	}

	public List getRoleList() {
		return roleList;
	}

	public void setRoleList(List roleList) {
		this.roleList = roleList;
	}

	public ISysParaService getSysParaService() {
		return sysParaService;
	}

	public void setSysParaService(ISysParaService sysParaService) {
		this.sysParaService = sysParaService;
	}

	public IPortalService getPortalService() {
		return portalService;
	}

	public void setPortalService(IPortalService portalService) {
		this.portalService = portalService;
	}


	public HashMap getPorletsMap() {
		return porletsMap;
	}

	public void setPorletsMap(HashMap porletsMap) {
		this.porletsMap = porletsMap;
	}

	public List getPorletsList() {
		return porletsList;
	}

	public void setPorletsList(List porletsList) {
		this.porletsList = porletsList;
	}

	public Map getUserSetting() {
		return userSetting;
	}

	public void setUserSetting(Map userSetting) {
		this.userSetting = userSetting;
	}

	public Map getLayout() {
		return layout;
	}

	public void setLayout(Map layout) {
		this.layout = layout;
	}

	public List getFirstLevelModuleList() {
		return firstLevelModuleList;
	}

	public void setFirstLevelModuleList(List firstLevelModuleList) {
		this.firstLevelModuleList = firstLevelModuleList;
	}

	public ISysSubSystemService getSysSubSystemService() {
		return sysSubSystemService;
	}

	public void setSysSubSystemService(ISysSubSystemService sysSubSystemService) {
		this.sysSubSystemService = sysSubSystemService;
	}

	public ISysModuleService getSysModuleService() {
		return sysModuleService;
	}

	public void setSysModuleService(ISysModuleService sysModuleService) {
		this.sysModuleService = sysModuleService;
	}

	public ISysUserShortcutService getSysUserShortcutService() {
		return sysUserShortcutService;
	}

	public void setSysUserShortcutService(
			ISysUserShortcutService sysUserShortcutService) {
		this.sysUserShortcutService = sysUserShortcutService;
	}

	public List getShortcutList() {
		return shortcutList;
	}

	public void setShortcutList(List shortcutList) {
		this.shortcutList = shortcutList;
	}

	public PortalForm getFilter() {
		return filter;
	}

	public void setFilter(PortalForm filter) {
		this.filter = filter;
	}

	public TblSYS_LOGINMSG getUser() {
		return user;
	}

	public void setUser(TblSYS_LOGINMSG user) {
		this.user = user;
	}

	public IPublicSysService getPublicSysService() {
		return publicSysService;
	}

	public void setPublicSysService(IPublicSysService publicSysService) {
		this.publicSysService = publicSysService;
	}

	public ISysLogInmsgService getSysLogInmsgService() {
		return sysLogInmsgService;
	}

	public void setSysLogInmsgService(ISysLogInmsgService sysLogInmsgService) {
		this.sysLogInmsgService = sysLogInmsgService;
	}

	public ISysUserPrivilegeService getSysUserPrivilegeService() {
		return sysUserPrivilegeService;
	}

	public void setSysUserPrivilegeService(
			ISysUserPrivilegeService sysUserPrivilegeService) {
		this.sysUserPrivilegeService = sysUserPrivilegeService;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public IAsyncTreeService getPortalTreeService() {
		return portalTreeService;
	}

	public void setPortalTreeService(IAsyncTreeService portalTreeService) {
		this.portalTreeService = portalTreeService;
	}

	public String getModule_id() {
		return module_id;
	}

	public void setModule_id(String module_id) {
		this.module_id = module_id;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getHelpMsg() {
		return helpMsg;
	}

	public void setHelpMsg(String helpMsg) {
		this.helpMsg = helpMsg;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public ISysUserPortalService getUserPortalService() {
		return userPortalService;
	}

	public void setUserPortalService(ISysUserPortalService userPortalService) {
		this.userPortalService = userPortalService;
	}

	public List<HashMap> getUserPorlets() {
		return userPorlets;
	}

	public void setUserPorlets(List<HashMap> userPorlets) {
		this.userPorlets = userPorlets;
	}

	public UserPortalForm getPortalForm() {
		return portalForm;
	}

	public void setPortalForm(UserPortalForm portalForm) {
		this.portalForm = portalForm;
	}

	public String getSubSystemJsonList() {
		return subSystemJsonList;
	}

	public void setSubSystemJsonList(String subSystemJsonList) {
		this.subSystemJsonList = subSystemJsonList;
	}

	public List getSubSystemList() {
		return subSystemList;
	}

	public void setSubSystemList(List subSystemList) {
		this.subSystemList = subSystemList;
	}

	public ISysUserPanelOrderService getSysUserPanelOrderService() {
		return sysUserPanelOrderService;
	}

	public void setSysUserPanelOrderService(
			ISysUserPanelOrderService sysUserPanelOrderService) {
		this.sysUserPanelOrderService = sysUserPanelOrderService;
	}

	public String portaljs() {
		return SUCCESS;
	}

	public String iframeResizeScript(){
		return SUCCESS;
	}

	public String loginIndex() {
		String userCode = user.getUSER_ID();
		String userPassword = user.getLOGIN_PASSWD();
		HashMap map = null;
		TblSYS_LOGINMSG user = new TblSYS_LOGINMSG();
		try {
			// 判断连接的库中是否存在TB_SYS_MANAGE_UNIT，TB_SYS_USER_PRIVILEGE管理单元用到的表，如果存在再去取用户的UNIT_ID
			String[] tablenames = { "TB_SYS_MANAGE_UNIT",
					"TB_SYS_USER_PRIVILEGE" };
			int tableCount = publicSysService.findUserTable(tablenames);

			map = sysLogInmsgService.validLogin(userCode, userPassword, tableCount);
			// TblSYS_POSTTIME log = new TblSYS_POSTTIME();
			// log.setEMPLOYEE_ID((String) map.get("LOGIN_ID"));
			// log.setLOGIN_ID((String) map.get("LOGIN_ID"));
			// log.setSTART_TIME(new Date());
			// String ID = PostTime.add(log);

			user.setCOMP_ID((String) map.get("COMP_ID"));
			user.setDEPT_ID((String) map.get("DEPT_ID"));
			user.setLOGIN_ID((String) map.get("LOGIN_ID"));
			user.setLOGIN_PASSWD((String) map.get("LOGIN_PASSWD"));

			String unit_idStr = "ALL";
			// 判断用户是否有其他管理单元的特权
			if (tableCount == 2) {
				unit_idStr = sysUserPrivilegeService
						.getUserPrivilegeStrByLogin_id((String) map
								.get("LOGIN_ID"));
				unit_idStr += (String) map.get("MANAGE_UNIT_ID") == null ? ""
						: (String) map.get("MANAGE_UNIT_ID");

				// 判断是否有管理单元没有则设置为所有权限
				if (unit_idStr != null && !"".equals(unit_idStr)) {
					user.setMANAGE_UNIT_ID(unit_idStr);
				} else {
					user.setMANAGE_UNIT_ID("ALL");
				}
			} else {
				user.setMANAGE_UNIT_ID("ALL");
			}
			user.setLOGIN_PHONE((String) map.get("LOGIN_PHONE"));
			user.setNAME((String) map.get("NAME"));
            user.setLOGIN_STATE(Integer.parseInt(map.get("LOGIN_STATE").toString()));
			user.setEMAIL_ADDR((String) map.get("EMAIL_ADDR"));
			user.setLOCKSTATE((String) map.get("LOCKSTATE"));

			// user.setLogId(ID);
			ServletActionContext.getRequest().getSession().setAttribute(TblSYS_LOGINMSG.SESSION_KEY, user);

			flag = "true";
		} catch (Exception sex) {
			log.info(sex);
			flag = sex.getMessage();
		}

		return SUCCESS;
	}

	private void setUser() throws Exception{
		String userCode = CommUtil.USER_ADMIN;
		String userPassword = "12345678";

		String[] tablenames = { "TB_SYS_MANAGE_UNIT", "TB_SYS_USER_PRIVILEGE" };
        int tableCount = publicSysService.findUserTable(tablenames);


        HashMap map = sysLogInmsgService.validLoginBySSO(userCode, userPassword,
				tableCount);

        user.setLOGIN_ID(userCode);
		user.setNAME("管理员");
		user.setStylePath("/nresources/default");
		user.setLOCAL_PHONE("6530402");
		user.setLOGIN_PHONE("18612779823");
		user.setEMAIL_ADDR("zdj@163.com");
		user.setDEPT_ID(map.get("DEPT_ID").toString());
		user.setMENU_TYPE("1");
		// 用户拥有的角色
        TblSYS_USER_ROLE rol = new TblSYS_USER_ROLE();
        rol.setLOGIN_ID(user.getLOGIN_ID());
        user.setRoles(sysRoleService.findForRoleListByLonginId(rol));

        String unit_idStr = "ALL";
		// 判断用户是否有其他管理单元的特权
		if (tableCount == 2) {
			unit_idStr = sysUserPrivilegeService.getUserPrivilegeStrByLogin_id(user.getLOGIN_ID());
			unit_idStr += (String) map.get("UNIT_ID") == null ? "" : (String) map.get("UNIT_ID");

			// 判断是否有管理单元没有则设置为所有权限
			if (unit_idStr != null && !"".equals(unit_idStr)) {
				user.setMANAGE_UNIT_ID(unit_idStr);
			} else {
				user.setMANAGE_UNIT_ID("ALL");
			}
		} else {
			user.setMANAGE_UNIT_ID("ALL");
		}


		ServletActionContext.getRequest().getSession().setAttribute(BaseConst.SESSION_USER_KEY, user);
	}

	public String login() throws Exception{
//		this.setUser();
		TblSYS_LOGINMSG user = this.getCurrentUser();
		System.out.println("user:"+user);
		if(user!=null){
			if(user.getLOGIN_ID().equalsIgnoreCase(CommUtil.USER_ADMIN)){
				subSystemList = sysModuleService.findModuleListByParentId("0");
			}else{
				subSystemList = sysModuleService.findModuleListByLoginIDAndParentId(user.getLOGIN_ID(), "0");
			}

			try{
                Iterator<HashMap> iter = subSystemList.iterator();
                while(iter.hasNext()){
                    HashMap map = iter.next();
                    if(map.get("MODULE_PATH")!=null && "1".equals(map.get("SSO_TYPE")))
                        map.put("MODULE_PATH", UrlSSOUtil.encryptUrl(map.get("MODULE_PATH").toString(), this.getCurrentUser().getLOGIN_ID()));
                    if("0".equals(map.get("MODULE_ENABLE").toString())){
                        iter.remove();
                    }
                }

			}catch(Exception e){
				e.printStackTrace();
			}

			subSystemJsonList = JSONUtil.toJSON(subSystemList);

			shortcutList = sysUserShortcutService.findShortcutListByLoginID(user.getLOGIN_ID());

			String project_name = ""+sysParaService.findSysParaByParaId("PROJECT_NAME").get("PARA_VALUE");
			String portal_link = ""+sysParaService.findSysParaByParaId("PORTAL_LINK").get("PARA_VALUE");

			filter.setPROJECT_NAME(project_name);
			filter.setPORTAL_LINK(portal_link);

			filter.setMenuType(user.getMENU_TYPE());
		}

		return SUCCESS;
	}

	public String getPanelInfo(){
		// 取得用户信息
        TblSYS_LOGINMSG user = this.getCurrentUser();
        // 取得用户拥有的所有的porlets
        porletsList = portalService.findPorletsByUser(user);
        // 把allPorlets转换成HashMap(以PORLET_ID为key)便于查找

//        for (int i = 0; i < allPorlets.size(); i++) {
//        	porletsMap.put(allPorlets.get(i).get("PORLET_ID"), allPorlets.get(i));
//        }
        // 取得用户的设置
        userSetting = portalService.findUserSetting(user.getLOGIN_ID());
        layout = portalService.findLayoutById((String) userSetting.get("LAYOUT_ID"));
//        panelData.put("USER_SETTING", userSetting);
        panelData.put("LAYOUT_CONFIG", layout);
        panelData.put("PORLET_CONFIG", porletsList);
        return SUCCESS;
	}
	/**
	 * panel全屏
	 * @return
	 */
	public String fullScreenPanel(){
		return SUCCESS;
	}
	/**
	 * 工作区全屏
	 * @return
	 */
	public String fullWorkArea(){
		return SUCCESS;
	}

	public String findPorletById() {
		String porlet_id = this.getRequest().getParameter("PANEL_ID");
		Map map = portalService.findPorletById(porlet_id);
		panelData.put("PORLET_CONFIG", map);
		return SUCCESS;
	}

	/**
	 * 用户退出系统
	 */
	public String loginout() {
		LOGOUT_LINK = sysParaService.findSysParaByParaId("PORTAL_LOGOUT").get("PARA_VALUE").toString();

		return SUCCESS;
	}

	public String logout() throws IOException {
		Object userId = this.getRequest().getParameter("changeUserId");
		Properties loginProps = new Properties();
		loginProps.load(Resources.getResourceAsStream("login.properties"));
		String loginUrl = loginProps.getProperty("loginUrl");
		String logoutUrl = loginUrl.replace("login", "logout");
		String portalUrl = loginUrl.replace("/cas/login", "/portal/");
		LOGOUT_LINK = logoutUrl + "?url=" + portalUrl;
		LOGOUT_LINK = loginProps.getProperty("logoutUrl", LOGOUT_LINK);
		if (userId != null) {
			user = sysLogInmsgService.findByUserCode(userId.toString());
			LOGOUT_LINK = logoutUrl + "?service=" + URLEncoder.encode(loginUrl + "?service=" + portalUrl + "&name=" + user.LOGIN_ID + "&psw=" + user.LOGIN_PASSWD, "utf8");
		}
		getSession().invalidate();
		return SUCCESS;
	}

	public String logoutForChangeUser(){
		LOGOUT_LINKS = sysParaService.findSysParaByParaIdEndWith("_LOGOUT");
		return SUCCESS;
	}


	/**
	 * 显示用户列表
	 */
	public String loadListUser() {

		String midId = this.getRequest().getParameter("DEPT_ID");

		TblSYS_LOGINMSG curUser = this.getCurrentUser();
		String unit_id = curUser.getMANAGE_UNIT_ID();
		// 为每个unit_id添加'方便DAO中拼凑SQL
		unit_id = unit_id.replaceAll(",", "','");
		// List lst = userDao.findListByDeparyType(deptType, midId);

		// liuweic modify 20091118
		String DeptID = ((String) curUser.getDEPT_ID()).substring(0, 3);
		IPage result = sysLogInmsgService.findListByDeparyTypeAndUnit(midId, this.getPageForm());

        this.setResult(result);

		return SUCCESS;
	}

	// qinjie add 人员列表查询
	public String findByUserIDAndUserName() {
		String midId = this.getRequest().getParameter("DEPT_ID");

		String login_id = (theForm.getUserId()).trim();
		String userName = (theForm.getUserName()).trim();

		TblSYS_LOGINMSG user = this.getCurrentUser();
		String DeptID = ((String) user.getDEPT_ID()).substring(0, 3);
		IPage result = sysLogInmsgService.findListByDeparyTypeAndUnit(login_id, userName, midId, this.getPageForm());

		this.setResult(result);

		return SUCCESS;
	}

	/**
	 * 显示用户列表--request
	 */
	public String loadListUserByDepartIdForRequest() {

		String deptId = theForm.getDEPT_ID();

		IPage result = sysLogInmsgService.findListByDeparyType("dept", deptId, this.getPageForm());

		this.setResult(result);

		return SUCCESS;
	}




	/**
	 * 显示未被冻结的用户列表
	 */
	public String unfrozenList() {
		return SUCCESS;

	}

	/**
	 * 显示未用户历史列表
	 */
	public String loadPostTime() {
		return SUCCESS;

	}
	public String loadPostTimeQueryJson() {

		try{
			IPage result = sysPostTimeService.findPostTimeList(this.getPageForm());

			this.setResult(result);
		}catch(Exception e){
			e.printStackTrace();
		}
		return SUCCESS;

	}

	/**
	 * 日志列表
	 *
	 */
	public String loadListLog() {
		return SUCCESS;

	}
	public String loadListLogQueryJson() {
		try{
			String userId = theForm.getLOGIN_ID();
            if(("").equals(userId)){
                userId =null;
            }
			IPage result = sysLogService.findListByPK(userId, this.getPageForm());
			this.setResult(result);
		}catch(Exception e){
			e.printStackTrace();
		}
		return SUCCESS;
	}

	public String loadLogContent(){
		try{
			String id = this.getRequest().getParameter("ID");
			IPage result = sysLogService.findLogByPK(id, this.getPageForm());
			this.setResult(result);
		}catch(Exception e){
			e.printStackTrace();
		}
		return SUCCESS;
	}

	// 级联下拉框
	public String personSelect() throws Exception{

		String dept_id = this.getRequest().getParameter("id");

		// 返回的内容为JSON，格式为{‘’：‘’，‘’：‘’，‘’：‘’}
		List list = null;
		StringBuffer buff = new StringBuffer("{'':' ',");

		try{
			list = sysLogService.findUserList(new String(this.getRequest().getParameter("id").getBytes(
					"gb2312"), "GB2312"));

			if (list.size() > 0) {
				for (int z = 0; z < list.size(); z++) {
					HashMap obj = (HashMap) list.get(z);
					if (z != 0) {
						buff.append(",");
					}
					buff.append("'");
					buff.append(obj.get("LOGIN_ID").toString());
					buff.append("':'");
					buff.append(obj.get("NAME").toString());
					buff.append("'");
				}
			} else {
				buff.deleteCharAt(buff.length() - 1);
			}

			buff.append("}");
			flag = buff.toString();
		}catch(Exception e){
			throw e;
		}

		return SUCCESS;
	}

	public String loginBySso() {

		TblSYS_LOGINMSG user = this.getCurrentUser();
		subSystemList = sysSubSystemService.findSubSystemListByLoginID(user.getLOGIN_ID());
		subSystemJsonList = JSONUtil.toJSON(subSystemList);

		shortcutList = sysUserShortcutService.findShortcutListByLoginID(user.getLOGIN_ID());

		String project_name = ""+sysParaService.findSysParaByParaId("PROJECT_NAME").get("PARA_VALUE");
		String portal_link = ""+sysParaService.findSysParaByParaId("PORTAL_LINK").get("PARA_VALUE");

		filter.setPROJECT_NAME(project_name);
		filter.setPORTAL_LINK(portal_link);

		return SUCCESS;
	}

	public String selectLoginMsg() throws Exception{

		String login_id = this.getRequest().getParameter("login_id");
		String name = java.net.URLDecoder.decode(this.getRequest().getParameter("name"),
				"UTF-8");

		IPage result = sysLogInmsgService.findUserCodeLike(login_id, name, this.getPageForm());

		this.setResult(result);
		return SUCCESS;
	}


	/**
	 * 加载第一层节点
	 * @return
	 */
	public String loadAccordionItemByParentId(){
		List<HashMap> defaultModules;

		if(this.getCurrentUser().getLOGIN_ID().equalsIgnoreCase(CommUtil.USER_ADMIN)){
			defaultModules = sysModuleService.findModuleListByParentId(module_id);
		}else{
			defaultModules = sysModuleService.findModuleListByLoginIDAndParentId(this.getCurrentUser().getLOGIN_ID(), module_id);
		}

		try{
            Iterator<HashMap> iter = defaultModules.iterator();
            while(iter.hasNext()){
                HashMap map = iter.next();
                if(map.get("MODULE_PATH")!=null && "1".equals(map.get("SSO_TYPE")))
                    map.put("MODULE_PATH", UrlSSOUtil.encryptUrl(map.get("MODULE_PATH").toString(), this.getCurrentUser().getLOGIN_ID()));
                if("0".equals(map.get("MODULE_ENABLE").toString())){
                    iter.remove();
                }
            }
		}catch(Exception e){
			e.printStackTrace();
		}
		flag = JSONUtil.toJSON(defaultModules);
		return SUCCESS;
	}

	/**
	 * 根据accordion中的id加载各级子节点
	 * @return
	 */
	public String loadSubNodeByModuleId(){
		try{
			TreeNode treeNode = new TreeNode();
			treeNode.setpId(getId());
			List<TreeNode> treeNodeList = portalTreeService.getSubNodes(this.getCurrentUser().getLOGIN_ID(), treeNode);
			flag = JSONUtil.toJSON(treeNodeList);
		}catch(Exception ex){
			ex.printStackTrace();
			return FAILURE;
		}
		return SUCCESS;
	}
	/**
	 * 根据父节点加载前三层节点
	 * @return
	 */
	public String loadAllNodeLevelByParentId() throws AppException{
		try{
			String loginId = null;
    		if(!this.getCurrentUser().getLOGIN_ID().equalsIgnoreCase(CommUtil.USER_ADMIN))
    			loginId = this.getCurrentUser().getLOGIN_ID();

			List modules = sysModuleService.loadAllNodeLevelByParentId(loginId, module_id);
            Iterator<TreeNode> iter = modules.iterator();
            while(iter.hasNext()){
                TreeNode node = iter.next();
                if("0".equals(node.getUserData("ENABLE"))){
                    iter.remove();
                }
            }
			flag = JSONUtil.toJSON(modules);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 加载个性化设置信息
	 * @return
	 */
	public String loadOldInfoOther(){
		try{
			theForm.setUserName(this.getCurrentUser().getNAME());
			theForm.setLocal_phone(this.getCurrentUser().getLOCAL_PHONE());
			theForm.setTelphone(this.getCurrentUser().getLOGIN_PHONE());
			theForm.setEmail(this.getCurrentUser().getEMAIL_ADDR());
			theForm.setMenuType(this.getCurrentUser().getMENU_TYPE());
			/*加载portal个性化信息*/
			// 取出该用户角色对应的所有porlet信息
			List<HashMap> roles = this.getCurrentUser().getRoles();

	//		userPorlets = sysUserPanelOrderService.findPanelOrder(this.getCurrentUser().getLOGIN_ID());

			// 取得用户信息
	        TblSYS_LOGINMSG user = this.getCurrentUser();
	        // 取得用户拥有的所有的porlets
	        userPorlets = portalService.findPorletsByROLE_ID(user.getRoles());
	        // 把allPorlets转换成HashMap(以PORLET_ID为key)便于查找

	//        for (int i = 0; i < allPorlets.size(); i++) {
	//        	porletsMap.put(allPorlets.get(i).get("PORLET_ID"), allPorlets.get(i));
	//        }
	        // 取得用户的设置
	        userSetting = portalService.findUserSetting(user.getLOGIN_ID());
	        String layout_id = "2";
	        if(userSetting!=null)
	        	layout_id = (String) userSetting.get("LAYOUT_ID");
	        else
	        	userSetting = new HashMap();
	        layout = portalService.findLayoutById(layout_id);

	        String str = "";
	        List panelList = sysUserPanelOrderService.findPanelOrder(user.getLOGIN_ID());
	        for(int i=0;i<panelList.size();i++){
	        	Map map = (Map)panelList.get(i);
	        	str += map.get("PANEL_ID") + ",";
	        }
	        if(str.length()>0)
	        	str = str.substring(0,str.length()-1);
	        userSetting.put("PORLETS", str);
		}catch(Exception e){
			e.printStackTrace();
		}

		return SUCCESS;
	}
	/**
	 * 保存用户设置
	 * @return
	 */
	public String saveUserSetting(){
		HashMap<String,Boolean> result = new HashMap<String,Boolean>();
		try{
			TblSYS_LOGINMSG user = this.getCurrentUser();
			String login_id = user.getLOGIN_ID();
			String PANEL_ID = portalForm.getPANEL_ID()[0];
			String PANEL_COLLECTS[] = portalForm.getPANEL_COLLECT().split(";");
			String menuType = portalForm.getMenuType();
//			String panels = "";
//			// 根据布局进行分配
//			layout = portalService.findLayoutById(PANEL_ID);
//			int columnSize = Integer.parseInt(layout.get("COLUMNS").toString());
//			HashMap<Integer,String> rowMaps = new HashMap<Integer,String>();
//			int idx = 0;
//			for(String panel : PANEL_COLLECTS){
//				int celNums = 0;
//				if(columnSize != 1){
//					celNums = idx/columnSize;
//				}
//				rowMaps.put(celNums, (rowMaps.get(celNums)==null?"":rowMaps.get(celNums))+","+panel);
//				idx ++;
//			}
//			// 将列与行合并
//			Set<Integer> keySet = rowMaps.keySet();
//			Iterator<Integer> keyIt = keySet.iterator();
//			for(;keyIt.hasNext();){
//				// 将第一个','号去掉
//				panels += ";" + rowMaps.get(keyIt.next()).substring(1);
//				
//			}
//			panels = panels.substring(1);
			portalService.updateUserSetting_LAYOUT(login_id, PANEL_ID);
//			portalService.updateUserSetting_PORLETS(login_id, panels);	
			List list = new ArrayList();
			for(int i=0;i<PANEL_COLLECTS.length;i++){
				if(!PANEL_COLLECTS[i].equals("")){
					HashMap map = new HashMap();
					map.put("LOGIN_ID", this.getCurrentUser().getLOGIN_ID());
					map.put("PANEL_ID", PANEL_COLLECTS[i]);
					map.put("PANEL_ORDER", i);
					list.add(map);
				}
			}
			sysUserPanelOrderService.updatePanelOrder(login_id, list);


			TblSYS_LOGINMSG loginmsg = sysLogInmsgService.findByUserCode(login_id);
			loginmsg.setMENU_TYPE(menuType);
			sysLogInmsgService.updateMenuType(loginmsg);

			result.put("result", true);
		}catch(Exception ex){
			result.put("result", false);
			ex.printStackTrace();
		}
		flag = JSONUtil.toJSON(result);
		this.setJSON(flag);
		return SUCCESS;
	}

	/**
	 * 校验用户输入的密码和后台密码是否匹配
	 * @return
	 */
	public String checkOldPasswordValid(){
		boolean rst = sysLogInmsgService.validPassword(this.getCurrentUser().getLOGIN_ID(), theForm.getPassword());
		flag = String.valueOf(rst);
		return SUCCESS;
	}


	/**
	 * 修改密码
	 *
	 */
	public String changePassword() {
		String userNewPassword = theForm.getPassword();
		boolean rst = sysLogInmsgService.changePasswordByUser(this.getCurrentUser().getLOGIN_ID(), userNewPassword);
		HashMap<String,Boolean> jsonMap = new HashMap<String,Boolean>();
		jsonMap.put("result", rst);
		flag = JSONUtil.toJSON(jsonMap);
		this.setJSON(flag);
		return SUCCESS;
	}

	/**
	 * modifyPersonInfo:(保存用户手机号，固定电话，邮件地址信息)
	 */
	public String modifyPersonInfo() {
		flag = "true";
		try{
			sysLogInmsgService.modifyTbSysLoginMsg(this.getCurrentUser().getLOGIN_ID(),theForm);
            HttpSession session = ServletActionContext.getRequest().getSession();
            TblSYS_LOGINMSG user = (TblSYS_LOGINMSG)session.getAttribute(BaseConst.SESSION_USER_KEY);
            getCurrentUser().setLOCAL_PHONE(theForm.getLocal_phone());
            getCurrentUser().setLOGIN_PHONE(theForm.getTelphone());
            getCurrentUser().setEMAIL_ADDR(theForm.getEmail());
		}catch(Exception e){
			e.printStackTrace();
			flag = e.getMessage();
		}
		HashMap<String,String> jsonMap = new HashMap<String,String>();
		jsonMap.put("result", flag);
		flag = JSONUtil.toJSON(jsonMap);
		this.setJSON(flag);
		return SUCCESS;
	}

	public String tohelper(){
		helpMsg = portalService.loadHelperByHelpId(helpId);
		return SUCCESS;
	}

	public String saveHelpInfo(){
		HashMap<String,Boolean> result = new HashMap<String,Boolean>();
		try{

			System.out.println(content);
			portalService.updateHelpeInfo(helpId , content);
			result.put("result", true);
		}catch(Exception ex){
			result.put("result", false);
		}
		this.setJSON(JSONUtil.toJSON(result));
		return SUCCESS;
	}

	public String getHelpId() {
		return helpId;
	}

	public void setHelpId(String helpId) {
		this.helpId = helpId;
	}

	public HashMap<String, Map> getPanelData() {
		return panelData;
	}

	public void setPanelData(HashMap<String, Map> panelData) {
		this.panelData = panelData;
	}
	/**
	 * 拖动panel后保存排列顺序
	 * @return
	 */
	public String savePanelOrder(){
		try{
			String panelIds = this.getRequest().getParameter("panelIds");
			String array[] = panelIds.split(";");
			List list = new ArrayList();
			for(int i=0;i<array.length;i++){
				if(!array[i].equals("")){
					String[] panels = array[i].split(",");
					HashMap map = new HashMap();
					map.put("LOGIN_ID", this.getCurrentUser().getLOGIN_ID());
					map.put("PANEL_ID", panels[0]);
					map.put("PANEL_ORDER", i);
					map.put("GROUPNAME", panels[1]);
					list.add(map);
				}
			}

			sysUserPanelOrderService.updatePanelOrder(this.getCurrentUser().getLOGIN_ID(), list);
		}catch(Exception e){
			e.printStackTrace();
		}

		return SUCCESS;
	}

}
